package com.junjiao.util.db;

import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBAddress;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
 * Mongodb操作工具类
 *
 * @author jiaojun
 * @email:junjiao.j@gmail.com
 * @version:v0.2
 * @date:2012-1-17
 */
public class MongodbUtil {
	private DB db;//类唯一的Mongo实例
	private static MongodbUtil template;//类的唯一实例。根据Mongo的API，一个JVM只能有一个实例
	private String collectionName;//用于保存DBCollection名称
	
	/**
	 * 获取Mongodb操作实例
	 * @param ServerAddress 
	 * @param port
	 * @param DBName 数据库名
	 * @param CollName 表名
	 * @return
	 * @throws UnknownHostException
	 * @throws MongoException
	 */
	public static MongodbUtil getInstance (String ServerAddress,int port,String DBName,String CollName) throws UnknownHostException, MongoException{		
		if (null == template){
			template = new MongodbUtil(ServerAddress, port, DBName, CollName);
		}
		return template;
	}
	
	private MongodbUtil(String ServerAddress,int port,String DBName,String CollName) throws UnknownHostException, MongoException{
		Mongo mongo = new Mongo(new DBAddress(ServerAddress,port,DBName));
		db = mongo.getDB(DBName);
		collectionName = CollName;
	}
	
	 /**
     * 增加
     * @param obj
     */
    public void add(DBObject obj){
        DBCollection coll=db.getCollection(collectionName);
        coll.insert(obj);
    }
    /**
     * 删除
     * @param obj
     */
    public void delete(DBObject obj){
    	DBCollection coll=db.getCollection(collectionName);
        coll.remove(obj);
    }
    
    /**
     * 修改
     */
    public void modify(DBObject orig,DBObject update){
    	DBCollection coll=db.getCollection(collectionName);
        coll.update(orig, update, true, false);
    }
    
    /**
     * 查询
     * 子项查询：obj.put("answers", new BasicDBObject("$size", 3));
     */
    public DBCursor select(DBObject obj){
    	DBCollection coll=db.getCollection(collectionName);
        return coll.find(obj);
    }
	
	/**
	 * @param Key 需要查找的键
	 * @return 查找结果
	 * */
	public Object getValue(String Key){
		Object ret = null;
		boolean needBreak = false;
		Set<String> collection = db.getCollectionNames();
		
		for(String collName : collection){//遍历Collection名称
			
			DBCollection coll = db.getCollection(collName);
			if (null != coll){//如果获取的集合不为空，则获取游标并遍历内部数据
				
				DBCursor cursor = coll.find();
				
				while (cursor.hasNext()){
					@SuppressWarnings("rawtypes")
					Map map = cursor.next().toMap();
					if (map.containsKey(Key)){
						ret = map.get(Key);
						needBreak = true;
						break;
					}
				}
				if (needBreak){
					//如果needBreak为真，则证明已经在上述的while循环中被赋值，也就是已经查找到对象
					break;
				}
			}
		}
		return ret;
	}
	
	/**
	 * @param map 需要插入数据库的值
	 * @return 插入结果
	 */
	public boolean insertMongo(Map<String,Object> map){
		boolean ret = false;
		
		if (null != collectionName){
			DBCollection coll = db.getCollection(collectionName);			
			Set<String> set = map.keySet();
			BasicDBObject doc = new BasicDBObject();
			
			for (String key : set){				
				doc.put(key, map.get(key));
			}
			
			coll.insert(doc);
			ret = true;
		} else {
			return false;
		}
		
		return ret;
	}
	
	/**
	 * @return 获得数据表总行数
	 * 
	 * */
	public long count(){		
		DBCollection coll = db.getCollection(collectionName);
		if (null != coll){
			return coll.count();
		} else {
			return -1;
		}
	}
	
	public static void main(String[] args) {
		try {
			MongodbUtil mongodbUtil = MongodbUtil.getInstance("192.168.2.228", 2281, "qa", "qa");
			System.out.println(mongodbUtil.count());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
}
